<?php
namespace Todo\Service;

/**
 * 数据字典
 * User: yepanpan
 * Date: 2016/8/8
 * Time: 17:08
 */
class DictService extends BaseService
{
    private static $__INSTANCE = null;

    public static function getInstance(){
        if(!self::$__INSTANCE) self::$__INSTANCE = new DictService();

        return self::$__INSTANCE;
    }

    /**
     * 查询一个数据字典,并解析
     * @param string $dictCode 字典代码
     * @return bool|array
     */
   public function getDict($dictCode){
       $data = D('Todo/Sys/Dict')->findByField('code', strtoupper($dictCode));

       if(!$data) return false;

       if(!$data['value']) return false;

       $rows = explode("\n", $data['value']);
       if(!$rows) return false;

       $map = array();
       foreach ($rows as $row){
           if(!trim($row)) continue;
           $rd = explode('=', $row);
           $map[trim($rd[0])] = trim($rd[1]);
       }
       $data['map'] = $map;

       return $data;
   }

    /**
     * 根据值查询某个数据字典的标题
     * @param string $dictCode 字典代码
     * @param string $val 字典的值
     * @return bool|string
     */
    public function getDictTitle($dictCode, $val){
        $data = $this->getDict($dictCode);
        if(!$data) return false;

        return $data['map'][$val];
    }

    /**
     * 根据标题查询某个数据字典的值
     * @param $dictCode 字典代码
     * @param $title 标题
     * @return bool|mixed
     */
    public function getDictValue($dictCode, $title){
        $data = $this->getDict($dictCode);
        if(!$data) return false;

        return array_search($title, $data['map']);
    }
}